package com.hisense.ovcloud.mqtt.monitor.service;

import com.hisense.ovcloud.commons.dto.req.MqttThirdPartySetCmdReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class MqttClients {
    private final WebClient webClient;

    @Value("${business.mqttWarehouseUrl:http://ac-mqtt-business:5810}")
    private String mqttBusinessUrl;

    public MqttClients(@Qualifier("base") WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<Boolean> sendCmd(int domain, int subDomain, String wifiId, String payload){
        log.info("sendCmd");
        return webClient.post()
                .uri(mqttBusinessUrl + "/setCmd")
                .body(Mono.just(MqttThirdPartySetCmdReq.builder()
                        .majorDomainId(domain)
                        .subDomainId(subDomain)
                        .physicalId(wifiId)
                        .payload(payload)
                        .build()
                ), MqttThirdPartySetCmdReq.class)
                .retrieve()
                .bodyToMono(Boolean.class)
                .doOnSuccess(res -> {
                    log.info("succeed to sendCmd to wifiId {}", wifiId);
                })
                .doOnError(err -> log.error("failed to sendCmd to wifiId {}", wifiId, err));
    }

    public Mono<Boolean> connectItSelf(){
        return webClient.post()
                .uri( "http://localhost:8080/monitor")
                .retrieve()
                .toBodilessEntity()
                .zipWhen(r -> Mono.just(true), (x, y)->y);
    }
}
